package com.dingdang.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dingdang.entity.TbCarGoods;
import com.dingdang.service.EsService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

@Service
public class EsServiceImpl implements EsService {

    @Resource
    private RestHighLevelClient client;

    @Override
    public TbCarGoods selectById(Long carId) {
        SearchRequest request = new SearchRequest("dingdangcar");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        MatchPhraseQueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery("car_id", carId);
        searchSourceBuilder.query(queryBuilder);
        searchSourceBuilder.sort("sort");

        request.source(searchSourceBuilder);

        TbCarGoods tbCarGoods = null;
        try {
            //调用方法进行通讯
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //获取结果
            SearchHit[] hits = response.getHits().getHits();
            for (SearchHit hit : hits) {
                //获取普通内容
                String sourceAsString = hit.getSourceAsString();
                //将普通内容转换成实体类类型
                tbCarGoods = JSONObject.parseObject(sourceAsString, TbCarGoods.class);
                return tbCarGoods;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
